var express = require('express');
var router = express.Router();
var query = require('../my_modules/sql');

router.post('/', function (req, res) {
    console.log("处理登陆请求。。。");
    var name = req.body.name;
    var pwd = req.body.password;
    var sql = "select * from users where name = '" + name + "'";
    console.log(sql);
    query(sql, function (qerr,result,fields) {
        if(result.length == 0){
            res.json({msg:'用户不存在',status:'fail'});
        }else{
            if(result[0].password == pwd){
                console.log("登陆成功");
                req.session.user = name;
                res.json({status:'ok', msg:'登陆成功', name:name});
            }else{
                res.json({msg:'密码错误',status:'fail'});
            }
        }
    });
});

router.get('/check', function (req, res) {
    console.log("check login");
    if(!req.session.user){
        console.log("user" + req.session.user);
        res.json({status:'fail', name:req.session.user});
    }else{
        console.log("user" + req.session.user);
        res.json({status:'ok', name:req.session.user});
    }
});

router.get('/loginout', function (req, res) {
    console.log("login out");
    if(!req.session.user){
        res.json({status:'fail', msg:"您还未登陆"});
    }else{
        delete req.session.user;
        res.json({status:'ok', msg:"bye bye"});
    }
});

module.exports = router;